//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using OpenLS.Spreadsheet.Parsing;

namespace OpenLS.Spreadsheet.Expressions
{
    class MultiWorksheetRangeReference: RangeReference
    {
        private readonly List<Worksheet> _worksheets;
        private readonly RangeReferenceInfo _info;

        public MultiWorksheetRangeReference(List<Worksheet> worksheets)
        {
            _worksheets = worksheets;
        }

        public override Worksheet Worksheet
        {
            get { throw new NotSupportedException(); }
        }

        protected override Range GetRange()
        {
            {
                CompositeRange result = new CompositeRange(Enumerable.Select(_worksheets, ws => (SimpleRange)_info.Project(ws).Range));
                return result;
            }

        }

        public override string Label
        {
            get {
                return StringEnumerable.Concat(_worksheets, ww => ww.SafeName, ":") + "!" + _info.Label;
                StringBuilder result = new StringBuilder();
                var last = this._worksheets[_worksheets.Count - 1];
                foreach (var worksheet in _worksheets)
                {
                    result.Append(worksheet.SafeName);
                    if (worksheet != last)
                        result.Append(":");
                }
                result.Append("!");
                result.Append(this._info.Label);
                return result.ToString();
            }
        }

        public override RangeReference Offset(CellRelativeAddress address)
        {
            return new MultiWorksheetRangeReference(this._worksheets);
        }

        internal override RangeReference Transposed(Cell target)
        {
            throw new NotImplementedException();
        }

        internal override RangeReference Projected(Worksheet targetWorksheet)
        {
            return this;
        }
    }
}